﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Forms;
using System.Xml.Linq;
using System.Text;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.采购管理.Server;
using CCWin.SkinClass;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间;
using System.Drawing;

namespace ERP_SaaS_WinForm.采购管理
{
    public partial class Procurement : Form
    {
        private bool _dataLoaded = false; // 防止重复加载
        
        public Procurement()
        {
            InitializeComponent();
            
            // 绑定Form.Load事件
            this.Load += Procurement_Load;
        }
        
        private void Procurement_Load(object sender, EventArgs e)
        {
            try
            {
                // 防止重复加载
                if (_dataLoaded) 
                {
                    return;
                }
                
                // 加载检验部门数据到下拉框
                LoadInspectionDepartments();
                
                // 修复Designer.cs控件可见性问题
                FixDesignerControlsVisibility();
                
                // 调整按钮尺寸，让文字显示更美观
                AdjustButtonSizes();
                
                // 恢复真正的添加事件绑定
                RestoreAddEvent();
                
                // 默认显示第一个标签页（质检添加）
                tabControl1.SelectedIndex = 0;
                
                // 绑定标签页切换事件
                tabControl1.SelectedIndexChanged += TabControl1_SelectedIndexChanged;
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 标签页切换事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (tabControl1.SelectedIndex == 1) // 质检显示标签页
                {
                    // 切换到质检显示标签页时加载数据
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        

        

        

        

        
        /// <summary>
        /// 调整按钮尺寸，让文字显示更美观
        /// </summary>
        private void AdjustButtonSizes()
        {
            try
            {
                // 调整添加按钮尺寸
                if (this.AddQua != null)
                {
                    this.AddQua.Size = new System.Drawing.Size(100, 35); // 增加宽度和高度
                }
                
                // 调整重置按钮尺寸
                if (this.DelQue != null)
                {
                    this.DelQue.Size = new System.Drawing.Size(100, 35); // 增加宽度和高度
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 恢复真正的添加事件绑定
        /// </summary>
        private void RestoreAddEvent()
        {
            try
            {
                // 恢复原来的添加事件绑定
                if (this.AddQua != null)
                {
                    // 确保绑定的是真正的添加事件
                    this.AddQua.Click -= this.TestAddButton_Click; // 移除测试事件
                    this.AddQua.Click += this.AddQua_Click; // 恢复真正的添加事件
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 立即测试按钮是否可点击
        /// </summary>
        
        /// <summary>
        /// 最终测试所有控件
        /// </summary>
        private void FinalTestAllControls()
        {
            try
            {
                // 检查所有主要控件
                var controls = new[]
                {
                    new { Name = "txtCode", Control = txtCode as Control },
                    new { Name = "txtName", Control = txtName as Control },
                    new { Name = "txteName", Control = txteName as Control },
                    new { Name = "DepName", Control = DepName as Control },
                    new { Name = "dateQue", Control = dateQue as Control },
                    new { Name = "AddQua", Control = AddQua as Control },
                    new { Name = "DelQue", Control = DelQue as Control }
                };
                
                foreach (var item in controls)
                {
                    if (item.Control != null)
                    {
                        // 静默检查控件状态
                    }
                }
                
                // 检查AddQua按钮状态
                if (AddQua != null)
                {
                    // 尝试最后一次修复
                    AddQua.Visible = true;
                    AddQua.Enabled = true;
                    AddQua.BringToFront();
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 直接修复Designer.cs中的控件可见性问题
        /// </summary>
        private void FixDesignerControlsVisibility()
        {
            try
            {
                // 强制设置所有控件的可见性
                if (this.txtCode != null) 
                { 
                    this.txtCode.Visible = true; 
                    this.txtCode.BringToFront();
                   // BeautifyTextBox(this.txtCode);
                }
                
                if (this.txtName != null) 
                { 
                    this.txtName.Visible = true; 
                    this.txtName.BringToFront();
                   // BeautifyTextBox(this.txtName);
                }
                
                if (this.txteName != null) 
                { 
                    this.txteName.Visible = true; 
                    this.txteName.BringToFront();
                    //BeautifyTextBox(this.txteName);
                }
                
                // 美化备注文本框（多行文本框）
                if (this.RedtxtReark != null)
                {
                    this.RedtxtReark.Visible = true;
                    this.RedtxtReark.BringToFront();
                   // BeautifyMultiLineTextBox(this.RedtxtReark);
                }
                
                if (this.DepName != null) 
                { 
                    this.DepName.Visible = true; 
                    this.DepName.BringToFront();
                    BeautifyComboBox(this.DepName);
                }
                
                if (this.dateQue != null) 
                { 
                    this.dateQue.Visible = true; 
                    this.dateQue.BringToFront();
                    //BeautifyDateTimePicker(this.dateQue);
                }
                
                if (this.AddQua != null) 
                { 
                    this.AddQua.Visible = true; 
                    this.AddQua.BringToFront();
                    BeautifyButton(this.AddQua, Color.FromArgb(52, 152, 219), Color.White);
                }
                
                if (this.DelQue != null) 
                { 
                    this.DelQue.Visible = true; 
                    this.DelQue.BringToFront();
                    BeautifyButton(this.DelQue, Color.FromArgb(231, 76, 60), Color.White);
                }
                
                // 修复butName按钮（质检人员选择按钮）
                if (this.butName != null) 
                { 
                    this.butName.Visible = true; 
                    this.butName.Enabled = true;
                    this.butName.BringToFront();
                    BeautifyButton(this.butName, Color.FromArgb(46, 204, 113), Color.White);
                }
                
                // 修复标签页
                if (this.tabPage1 != null) 
                { 
                    this.tabPage1.Visible = true;
                }
                
                // 强制刷新
                this.Invalidate();
                this.Update();
                this.Refresh();
                Application.DoEvents();
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 美化多行文本框
        /// </summary>
        private void BeautifyMultiLineTextBox(TextBox textBox)
        {
            try
            {
                textBox.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);
                textBox.BorderStyle = BorderStyle.FixedSingle;
                textBox.BackColor = Color.FromArgb(248, 249, 250);
                textBox.ForeColor = Color.FromArgb(33, 37, 41);
                textBox.Multiline = true;
                textBox.ScrollBars = ScrollBars.Vertical;
                textBox.Size = new Size(textBox.Width, 60);
                
                // 添加圆角效果
                textBox.Paint += (sender, e) =>
                {
                    var rect = new Rectangle(0, 0, textBox.Width - 1, textBox.Height - 1);
                    using (var path = GetRoundedRectangle(rect, 4))
                    {
                        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        using (var brush = new SolidBrush(textBox.BackColor))
                        {
                            e.Graphics.FillPath(brush, path);
                        }
                        using (var pen = new Pen(Color.FromArgb(206, 212, 218), 1))
                        {
                            e.Graphics.DrawPath(pen, path);
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 美化文本框
        /// </summary>
        private void BeautifyTextBox(TextBox textBox)
        {
            try
            {
                textBox.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);
                textBox.BorderStyle = BorderStyle.FixedSingle;
                textBox.BackColor = Color.FromArgb(248, 249, 250);
                textBox.ForeColor = Color.FromArgb(33, 37, 41);
                textBox.Size = new Size(textBox.Width, 28);
                
                // 添加圆角效果（通过自定义绘制）
                textBox.Paint += (sender, e) =>
                {
                    var rect = new Rectangle(0, 0, textBox.Width - 1, textBox.Height - 1);
                    using (var path = GetRoundedRectangle(rect, 4))
                    {
                        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        using (var brush = new SolidBrush(textBox.BackColor))
                        {
                            e.Graphics.FillPath(brush, path);
                        }
                        using (var pen = new Pen(Color.FromArgb(206, 212, 218), 1))
                        {
                            e.Graphics.DrawPath(pen, path);
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 美化下拉框
        /// </summary>
        private void BeautifyComboBox(ComboBox comboBox)
        {
            try
            {
                comboBox.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);
                comboBox.BackColor = Color.FromArgb(248, 249, 250);
                comboBox.ForeColor = Color.FromArgb(33, 37, 41);
                comboBox.FlatStyle = FlatStyle.Flat;
                comboBox.Size = new Size(comboBox.Width, 28);
                
                // 设置下拉箭头颜色
                comboBox.DrawMode = DrawMode.OwnerDrawFixed;
                comboBox.DrawItem += (sender, e) =>
                {
                    e.DrawBackground();
                    if (e.Index >= 0)
                    {
                        var item = comboBox.Items[e.Index];
                        if (item != null)
                        {
                            using (var brush = new SolidBrush(e.ForeColor))
                            {
                                e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds);
                            }
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 美化日期选择器
        /// </summary>
        private void BeautifyDateTimePicker(DateTimePicker dateTimePicker)
        {
            try
            {
                dateTimePicker.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);
                dateTimePicker.BackColor = Color.FromArgb(248, 249, 250);
                dateTimePicker.ForeColor = Color.FromArgb(33, 37, 41);
                dateTimePicker.Format = DateTimePickerFormat.Short;
                dateTimePicker.Size = new Size(dateTimePicker.Width, 28);
                
                // 设置日历样式
                dateTimePicker.CalendarFont = new Font("Microsoft YaHei UI", 9F, FontStyle.Regular);
                dateTimePicker.CalendarForeColor = Color.FromArgb(33, 37, 41);
                dateTimePicker.CalendarMonthBackground = Color.FromArgb(248, 249, 250);
                dateTimePicker.CalendarTitleBackColor = Color.FromArgb(52, 152, 219);
                dateTimePicker.CalendarTitleForeColor = Color.White;
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 美化按钮
        /// </summary>
        private void BeautifyButton(Button button, Color backColor, Color foreColor)
        {
            try
            {
                button.Font = new Font("Microsoft YaHei UI", 9F, FontStyle.Bold);
                button.BackColor = backColor;
                button.ForeColor = foreColor;
                button.FlatStyle = FlatStyle.Flat;
                button.FlatAppearance.BorderSize = 0;
                button.FlatAppearance.MouseOverBackColor = Color.FromArgb(
                    Math.Max(0, backColor.R - 20),
                    Math.Max(0, backColor.G - 20),
                    Math.Max(0, backColor.B - 20)
                );
                button.FlatAppearance.MouseDownBackColor = Color.FromArgb(
                    Math.Max(0, backColor.R - 40),
                    Math.Max(0, backColor.G - 40),
                    Math.Max(0, backColor.B - 40)
                );
                button.Cursor = Cursors.Hand;
                button.Size = new Size(button.Width, 32);
                
                // 添加圆角效果
                button.Region = new Region(GetRoundedRectangle(new Rectangle(0, 0, button.Width, button.Height), 6));
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 创建圆角矩形路径
        /// </summary>
        private System.Drawing.Drawing2D.GraphicsPath GetRoundedRectangle(Rectangle rect, int radius)
        {
            var path = new System.Drawing.Drawing2D.GraphicsPath();
            path.AddArc(rect.X, rect.Y, radius, radius, 180, 90);
            path.AddArc(rect.Width - radius, rect.Y, radius, radius, 270, 90);
            path.AddArc(rect.Width - radius, rect.Height - radius, radius, radius, 0, 90);
            path.AddArc(rect.X, rect.Height - radius, radius, radius, 90, 90);
            path.CloseFigure();
            return path;
        }
        
        /// <summary>
        /// 加载数据到质检显示页面
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 只显示一次列数信息
                // 静默检查列数
                
                string apiUrl = "http://localhost:5117/api/Supplier/GetQulityInfo";
                
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    var apiResponse = JsonConvert.DeserializeObject<QualityApiResponse>(jsonResponse);
                    
                    if (apiResponse.code == 200 && apiResponse.data != null && apiResponse.data.Count > 0)
                    {
                        // 清空现有数据
                        PlanDataList.Rows.Clear();
                        
                        // 手动添加数据行
                        foreach (var item in apiResponse.data)
                        {
                            int rowIndex = PlanDataList.Rows.Add();
                            
                            try
                            {
                                // 设置每个单元格的值
                                if (PlanDataList.Columns.Count > 0)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[0].Value = item.quaId;
                                }
                                
                                if (PlanDataList.Columns.Count > 1)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[1].Value = item.qualityInspector;
                                }
                                
                                if (PlanDataList.Columns.Count > 2)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[2].Value = item.quaState ? "合格" : "不合格";
                                }
                                
                                if (PlanDataList.Columns.Count > 3)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[3].Value = item.quaCode;
                                }
                                
                                if (PlanDataList.Columns.Count > 4)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[4].Value = item.quaName;
                                }
                                
                                if (PlanDataList.Columns.Count > 5)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[5].Value = item.quaDate.ToString("yyyy-MM-dd");
                                }
                                
                                if (PlanDataList.Columns.Count > 6)
                                {
                                    PlanDataList.Rows[rowIndex].Cells[6].Value = item.insDepName;
                                }
                            }
                                                catch (Exception cellEx)
                    {
                        // 静默处理单元格错误
                    }
                        }
                    }
                                    else
                {
                    // API返回数据为空或失败
                }
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }
        
        /// <summary>
        /// 加载检验部门数据到下拉框
        /// </summary>
                private async void LoadInspectionDepartments()
        {
            try
            {
                // 检查DepName控件是否存在
                if (DepName == null)
                {
                    // DepName控件为null
                    return;
                }
                
                string apiUrl = "http://localhost:5117/api/Supplier/GetInspectionDepInfo";
                
                using (HttpClient client = new HttpClient())
                {
                    var response = await client.GetAsync(apiUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse = await response.Content.ReadAsStringAsync();
                    
                    var apiResponse = JsonConvert.DeserializeObject<InspectionDepApiResponse>(jsonResponse);
                    
                    if (apiResponse.code == 200 && apiResponse.data != null && apiResponse.data.Count > 0)
                    {
                        // 清空现有数据
                        DepName.Items.Clear();
                        
                        // 添加默认选项
                        DepName.Items.Add(new DepInsop { insDepId = 0, insDepName = "请选择部门" });
                        
                        // 添加部门数据
                        foreach (var dept in apiResponse.data)
                        {
                            DepName.Items.Add(dept);
                        }
                        
                        // 设置显示和值属性
                        DepName.DisplayMember = "insDepName";
                        DepName.ValueMember = "insDepId";
                        
                        // 默认选择第一项
                        DepName.SelectedIndex = 0;
                    }
                    else
                    {
                        // 添加默认选项
                        DepName.Items.Add(new DepInsop { insDepId = 0, insDepName = "请选择部门" });
                        DepName.SelectedIndex = 0;
                    }
                }
            }
            catch (Exception ex)
            {
                // 静默处理错误

                // 添加默认选项
                DepName.Items.Add(new DepInsop { insDepId = 0, insDepName = "请选择部门" });
                DepName.SelectedIndex = 0;
            }
        }
        
        /// <summary>
        /// 质检信息API响应结果
        /// </summary>
        public class QualityApiResponse
        {
            public string msg { get; set; }
            public int code { get; set; }
            public List<PlanData> data { get; set; }
        }
        
        /// <summary>
        /// 质检数据模型 - 使用你的真实API字段名称
        /// </summary>
        public class PlanData
        {
            public int quaId { get; set; }           // 主键
            public string quaCode { get; set; }      // 质检编号
            public string quaName { get; set; }      // 质检名称
            public DateTime quaDate { get; set; }    // 软件日期
            public string insDepName { get; set; }   // 质检部门名称
            public string qualityInspector { get; set; } // 质检人
            public bool quaState { get; set; }       // 质检完商品的状态 0-未合格 1-已合格
        }

        private void skinLabel1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 测试添加按钮是否正常工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void TestAddButton_Click(object sender, EventArgs e)
        {
            // 测试方法已清空
        }

        private async void AddQua_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段（除了下拉框都要验证）
                if (string.IsNullOrWhiteSpace(txtCode.Text.Trim()))
                {
                    MessageBox.Show("请输入检验单编号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtCode.Focus();
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(txtName.Text.Trim()))
                {
                    MessageBox.Show("请输入检验名称", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtName.Focus();
                    return;
                }
                
                if (string.IsNullOrWhiteSpace(txteName.Text.Trim()))
                {
                    MessageBox.Show("请选择检验人", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txteName.Focus();
                    return;
                }
                
                // 验证日期
                if (!DateTime.TryParse(dateQue.text, out DateTime reqDate))
                {
                    MessageBox.Show("请输入有效的来料日期", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    dateQue.Focus();
                    return;
                }
                
                // 验证备注（如果备注也是必填的话）
                if (string.IsNullOrWhiteSpace(RedtxtReark.Text.Trim()))
                {
                    MessageBox.Show("请输入备注信息", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    RedtxtReark.Focus();
                    return;
                }
                
                // 验证部门选择
                if (DepName.SelectedValue == null || DepName.SelectedValue.ToString() == "0")
                {
                    MessageBox.Show("请选择检验部门", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    DepName.Focus();
                    return;
                }
                
                // 获取选中的部门ID - 强制修复
                int selectedDepId = 0;
                
                // 获取选中的部门ID
               // int selectedDepId = 0;
                
                // 强制从选中项获取部门ID
                if (DepName.SelectedIndex > 0 && DepName.Items[DepName.SelectedIndex] is DepInsop selectedDept)
                {
                    selectedDepId = selectedDept.insDepId;
                }
                else if (DepName.SelectedValue != null && DepName.SelectedValue.ToString() != "0")
                {
                    selectedDepId = Convert.ToInt32(DepName.SelectedValue);
                }
                else
                {
                    // 最后的备选方案：遍历所有部门找到匹配的名称
                    string selectedText = DepName.Text;
                    foreach (var item in DepName.Items)
                    {
                        if (item is DepInsop dept && dept.insDepName == selectedText)
                        {
                            selectedDepId = dept.insDepId;
                            break;
                        }
                    }
                }
                
                var quaData = new QueAdd
                {
                    QuaCode = txtCode.Text.Trim(),
                    QuaName = txtName.Text.Trim(),
                    QuaDate = reqDate,
                    QualityInspector = txteName.Text.Trim(),
                    QuaRemark = RedtxtReark.Text.Trim(),
                    QuaDepId = selectedDepId,
                };
                
                string jsonData = JsonConvert.SerializeObject(quaData);
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage resqonse = await client.PostAsync("http://localhost:5117/api/Qulity/AddQuality", content);
                    if (resqonse.IsSuccessStatusCode)
                    {
                        string resopnseContent = await resqonse.Content.ReadAsStringAsync();
                        var apipesponse = JsonConvert.DeserializeObject<AddResponse>(resopnseContent);
                        if (apipesponse.code == 200)
                        {
                            // 显示成功弹窗
                            MessageBox.Show("质检信息添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // 清空表单
                            //ClearInputFields();
                            // 刷新列表
                            LoadData();
                        }
                        else
                        {
                            // 显示失败弹窗
                            MessageBox.Show($"质检信息添加失败：{apipesponse.msg}", "失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // HTTP请求失败
                        string errorContent = await resqonse.Content.ReadAsStringAsync();
                        MessageBox.Show($"HTTP请求失败：{resqonse.StatusCode}\n{errorContent}", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    
                }




            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加质检信息时出错: {ex.Message}");
            }
        }
        /// <summary>
        /// 清空输入框
        /// </summary>
        private void ClearInputFields()
        {
            txtCode.Text = string.Empty;
            txtName.Text = string.Empty;
            txteName.Text = string.Empty;
            dateQue.text = DateTime.Now.ToString("yyyy-MM-dd"); // 修复：使用text属性
            DepName.SelectedIndex = 0; // 选择"请选择部门"
        }
        
        /// <summary>
        /// 手动刷新数据按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshData_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception ex)
            {
                // 静默处理错误
            }
        }

        /// <summary>
        /// 部门信息模型
        /// </summary>
        public class DepInsop
        {
            /// <summary>
            /// 主键 - 匹配API返回的字段名
            /// </summary>
            public int insDepId { get; set; }
            /// <summary>
            /// 部门名称 - 匹配API返回的字段名
            /// </summary>
            public string insDepName { get; set; }
        }

        /// <summary>
        /// 清空输入框
        /// </summary>
       /* private void ClearInputFields()
        {
            txtCode.Text = string.Empty;
            txtName.Text = string.Empty;
            txteName.Text = string.Empty;
            dateQue.text = DateTime.Now.ToString("yyyy-MM-dd");
            DepName.SelectedIndex = 0; // 选择"请选择部门"
        }*/

        /// <summary>
        /// 获取选中的部门ID
        /// </summary>
        /// <returns>部门ID，如果没有选中则返回0</returns>
        private int GetSelectedDepartmentId()
        {
            if (DepName.SelectedItem != null && DepName.SelectedItem is DepInsop selectedDept)
            {
               // return selectedDept.InsDepId;
            }
            return 0; // 默认部门ID
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns>当前用户名</returns>
        private string GetCurrentUser()
        {
            // 这里需要根据你的用户登录系统来获取当前用户
            // 暂时返回默认值
            return "当前用户"; // 你需要替换为实际的用户获取逻辑
        }

        /// <summary>
        /// 重置按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DelQue_Click(object sender, EventArgs e)
        {
            ClearInputFields();
        }

        /// <summary>
        /// 质检信息API响应结果
        /// </summary>
        public class ApiResult
        {  
            public int code { get; set; }
            public string msg { get; set; }
            public object data { get; set; }
        }
        ///
        /// <summary>
        /// 部门选择改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DepName_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (DepName.SelectedItem != null && DepName.SelectedItem is DepInsop selectedDept)
            {
                // 如果选择的是"请选择部门"，给出提示
                /*if (selectedDept.InsDepId == 0)
                {
                    // 可以在这里添加提示逻辑
                    return;
                }*/
                
                // 选择有效部门后的处理
                // 可以在这里添加其他业务逻辑，比如：
                // - 更新其他相关控件
                // - 验证权限
                // - 记录操作日志等
            }
        }

        /// <summary>
        /// 检验部门API响应结果
        /// </summary>
        public class InspectionDepApiResponse
        {
            public string msg { get; set; }
            public int code { get; set; }
            public List<DepInsop> data { get; set; }
        }
        /// <summary>
        /// 触发用户的信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butName_Click(object sender, EventArgs e)
        {
            try
            {
                var selectProductForm = new Materials();
                if (selectProductForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了产品，将产品信息填充到对应的输入框
                    if (selectProductForm.SelectSupR != null)
                    {
                        var product = selectProductForm.SelectSupR;
                        txteName.Text = product.QIName;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开质检人员选择窗口失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

